package com.guoxin.jiyin.utils;

import com.guoxin.jiyin.service.impl.BlockChainsServiceImpl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import java.security.Key;
import java.security.SecureRandom;

public class SysUtils {


    private static final Logger log = LogManager.getLogger(BlockChainsServiceImpl.class);

    private static String aecKey = "what1234";

    public static String aesEncrypt(String text) throws Exception {

        SecureRandom sr = new SecureRandom();
        Key secureKey = getKey(aecKey);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
        byte[] bt = cipher.doFinal(text.getBytes());
        String strS = new BASE64Encoder().encode(bt);
        return strS;
    }

    public static Key getKey(String strKey) {
        try {
            if (strKey == null) {
                strKey = "";
            }
            KeyGenerator _generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            _generator.init(128, secureRandom);
            return _generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(" 初始化密钥出现异常 ");
        }
    }

    public static String aesDecrypt(String text) throws Exception {
        SecureRandom sr = new SecureRandom();
        Cipher cipher = Cipher.getInstance("AES");
        Key secureKey = getKey(aecKey);
        cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
        byte[] res = new BASE64Decoder().decodeBuffer(text);
        res = cipher.doFinal(res);
        return new String(res);
    }

}
